package com.jw.debezuim.utils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;

/**
 * @auther wangjianying
 * @date 2023/03/15 13:41
 */
public class BeanCopyUtil {
    public static  <T> void copyTargetNullField(T source, T target) {
        try {
            if (source == null || target == null) {
                return;
            }
            BeanInfo beanInfo = Introspector.getBeanInfo(target.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                if (propertyDescriptor.getWriteMethod() != null && propertyDescriptor.getReadMethod() != null) {
                    Object sourceFieldValue = propertyDescriptor.getReadMethod().invoke(source);
                    Object targetFieldValue = propertyDescriptor.getReadMethod().invoke(target);
                    if (sourceFieldValue != null && targetFieldValue == null) {
                        propertyDescriptor.getWriteMethod().invoke(target, sourceFieldValue);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static <T> void copySourceNotNullField(T source, T target) {
        try {
            if (source == null || target == null) {
                return;
            }
            BeanInfo beanInfo = Introspector.getBeanInfo(target.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                if (propertyDescriptor.getWriteMethod() != null && propertyDescriptor.getReadMethod() != null) {
                    Object sourceFieldValue = propertyDescriptor.getReadMethod().invoke(source);
                    if (sourceFieldValue != null) {
                        propertyDescriptor.getWriteMethod().invoke(target, sourceFieldValue);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
